package com.sdp.khy.baotou.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.khy.baotou.SendSms.SendSmsController;
import com.sdp.khy.baotou.db.khy_package.entity.KhyPackage;
import com.sdp.khy.baotou.db.khy_package.service.IKhyPackageService;
import com.sdp.khy.baotou.db.khy_package_logistics.entity.KhyPackageLogistics;
import com.sdp.khy.baotou.db.khy_package_logistics.service.IKhyPackageLogisticsService;
import com.sdp.khy.baotou.db.khy_transport.entity.KhyTransport;
import com.sdp.khy.baotou.db.khy_transport.service.IKhyTransportService;
import com.sdp.khy.baotou.db.khy_user.entity.KhyUser;
import com.sdp.khy.baotou.db.khy_user.service.IKhyUserService;
import com.sdp.khy.baotou.db.khy_user_adress.entity.KhyUserAdress;
import com.sdp.khy.baotou.db.khy_user_adress.service.IKhyUserAdressService;
import com.sdp.khy.baotou.db.khy_user_coupon.entity.KhyUserCoupon;
import com.sdp.khy.baotou.db.khy_user_coupon.service.IKhyUserCouponService;
import com.sdp.khy.baotou.db.khy_user_invoice.entity.KhyUserInvoice;
import com.sdp.khy.baotou.db.khy_user_invoice.service.IKhyUserInvoiceService;
import com.sdp.khy.baotou.utils.KhyConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/UserController")
public class UserController {

	@Autowired
	private Query query;

	@Autowired
	private IKhyUserAdressService userAdressService;

	@Autowired
	private IKhyPackageService packageService;

	@Autowired
	private IKhyTransportService transportService;

	@Autowired
	private IKhyUserInvoiceService userInvoiceService;
	
	@Autowired
	private IKhyUserService iKhyUserService;

	@Autowired
	private IKhyPackageLogisticsService packageLogisticsService;
	
	@Autowired
	private IKhyUserCouponService userCouponService;

	@PostMapping(value = "/savePackage")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> savePackage(@RequestBody KhyPackage khyPackage) {
		if(khyPackage == null) {
			return Result.error("信息为空");
		}
		if (StringUtils.isEmpty(khyPackage.getKeyId())) {
			khyPackage.setPackageNo(KhyConstants.getNo());
			khyPackage.setOrderTime(LocalDateTime.now());
			packageService.save(khyPackage);
			//更新步骤表
			KhyPackageLogistics packageLogistics = new KhyPackageLogistics();
			packageLogistics.setPackageId(khyPackage.getKeyId());
			packageLogistics.setPackageState(KhyConstants.快递状态_已下单.getCode());
			packageLogistics.setLogisticsTime(LocalDateTime.now());
			StringBuffer sbf = new StringBuffer();
			sbf.append("下单账号：");
			sbf.append(khyPackage.getUserNo());
			packageLogistics.setLogisticsDesc(sbf.toString());
			packageLogisticsService.save(packageLogistics);
			
			//如果是新用户，更新用户表isNew字段
			UpdateWrapper<KhyUser> updateWrapper = new UpdateWrapper<>();
			updateWrapper.lambda().eq(KhyUser::getUserNo, khyPackage.getUserNo())
				.set(KhyUser::getIsNew, KhyConstants.否.getCode());
			iKhyUserService.update(updateWrapper);
			
			if (!StringUtils.isEmpty(khyPackage.getCouponId())) {
				//如果优惠卷id不为空，需要更新优惠卷使用状态
				UpdateWrapper<KhyUserCoupon> updateWrapperCoupon = new UpdateWrapper<>();
				updateWrapperCoupon.lambda().eq(KhyUserCoupon::getKeyId, khyPackage.getCouponId())
					.set(KhyUserCoupon::getCouponStatus, KhyConstants.优惠卷状态_已使用.getCode());
				userCouponService.update(updateWrapperCoupon);
			}
			
		} else {
			packageService.updateById(khyPackage);

			//更新步骤表
			QueryWrapper<KhyPackageLogistics> queryWrapper = new QueryWrapper<KhyPackageLogistics>();
			queryWrapper.lambda().eq(KhyPackageLogistics::getPackageId, khyPackage.getKeyId())
				.eq(KhyPackageLogistics::getPackageState, KhyConstants.快递状态_已揽收.getCode());
			packageLogisticsService.remove(queryWrapper);
			KhyPackageLogistics packageLogistics = new KhyPackageLogistics();
			packageLogistics.setPackageId(khyPackage.getKeyId());
			packageLogistics.setPackageState(KhyConstants.快递状态_已揽收.getCode());
			packageLogistics.setLogisticsTime(LocalDateTime.now());
			StringBuffer sbf = new StringBuffer();
			sbf.append("揽收人：理货员");
			sbf.append(khyPackage.getTallyClerkName());
			packageLogistics.setLogisticsDesc(sbf.toString());
			packageLogisticsService.save(packageLogistics);
		}
		return Result.ok(khyPackage);
	}
	
	@PostMapping(value = "/cancelPackage")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> cancelPackage(@RequestBody KhyPackage khyPackage) {
		if(khyPackage == null) {
			return Result.error("信息为空");
		}
		if (!StringUtils.isEmpty(khyPackage.getKeyId())) {
			//只更新状态订单状态
			khyPackage.setPackageState(KhyConstants.快递状态_已作废.getCode());
			packageService.updateById(khyPackage);
			
			if (!StringUtils.isEmpty(khyPackage.getCouponId())) {
				//如果优惠卷id不为空，需要更新优惠卷使用状态
				UpdateWrapper<KhyUserCoupon> updateWrapperCoupon = new UpdateWrapper<>();
				updateWrapperCoupon.lambda().eq(KhyUserCoupon::getKeyId, khyPackage.getCouponId())
					.set(KhyUserCoupon::getCouponStatus, KhyConstants.优惠卷状态_可使用.getCode());
				userCouponService.update(updateWrapperCoupon);
			}

			return Result.ok(khyPackage);
		} else {
			return Result.error("订单信息不正确");
		}
	}
	
	@PostMapping(value = "/signPackage")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> signPackage(@RequestBody KhyPackage khyPackage) {
		if(khyPackage == null) {
			return Result.error("信息为空");
		}
		khyPackage.setPackageState(KhyConstants.快递状态_已签收.getCode());
		packageService.updateById(khyPackage);
		//更新步骤表
		QueryWrapper<KhyPackageLogistics> queryWrapper = new QueryWrapper<KhyPackageLogistics>();
		queryWrapper.lambda().eq(KhyPackageLogistics::getPackageId, khyPackage.getKeyId())
			.eq(KhyPackageLogistics::getPackageState, KhyConstants.快递状态_已签收.getCode());
		packageLogisticsService.remove(queryWrapper);
		KhyPackageLogistics packageLogistics = new KhyPackageLogistics();
		packageLogistics.setPackageId(khyPackage.getKeyId());
		packageLogistics.setPackageState(KhyConstants.快递状态_已签收.getCode());
		packageLogistics.setLogisticsTime(LocalDateTime.now());
		StringBuffer sbf = new StringBuffer();
		sbf.append("签收人：理货员");
		sbf.append(khyPackage.getTallyClerkName());
		packageLogistics.setLogisticsDesc(sbf.toString());
		packageLogisticsService.save(packageLogistics);
		return Result.ok(khyPackage);
	}

	@PostMapping(value = "/pageOrder")
	public Result<?> pageOrder(@RequestBody DataCenter dataCenter) {
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<KhyPackage>();
		queryWrapper.lambda().orderByDesc(KhyPackage::getOrderTime);
		return Result.ok(query.page(packageService, KhyPackage.class, dataCenter, queryWrapper));
	}

	@GetMapping(value = "/getOrderByPackageState")
	public Result<?> getOrderByPackageState(@RequestParam(name="packageState",required=true) String packageState,
			@RequestParam(name="startStation",required=false) String startStation) {
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<KhyPackage>();
		queryWrapper.lambda().eq(KhyPackage::getPackageState, packageState)
			.orderByDesc(KhyPackage::getOrderTime);
		if (!StringUtils.isEmpty(startStation)) {
			queryWrapper.lambda().eq(KhyPackage::getStartStation, startStation);
		}
		return Result.ok(packageService.list(queryWrapper));
	}

	@GetMapping(value = "/getOrderByPackageNo")
	public Result<?> getOrderByPackageNo(@RequestParam(name="packageNo",required=true) String packageNo) {
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<KhyPackage>();
		queryWrapper.lambda().eq(KhyPackage::getPackageNo, packageNo);
		KhyPackage khyPackage = packageService.getOne(queryWrapper, false);
		if(khyPackage == null){
			Result.error("订单未查到");
		}
		return Result.ok(khyPackage);
	}
	
	//模糊查询未签收的已送达快递单
	@GetMapping(value = "/queryOrderByPackageNo")
	public Result<?> queryOrderByPackageNo(@RequestParam(name="packageNo",required=true) String packageNo) {
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<KhyPackage>();
		queryWrapper.lambda().like(KhyPackage::getPackageNo, packageNo)
			.eq(KhyPackage::getPackageState, KhyConstants.快递状态_已送达.getCode())
			.orderByDesc(KhyPackage::getOrderTime);
		//控制返回结果的最大记录数
		DataCenter dataCenter = new DataCenter();
		dataCenter.setPageNo(1);
		dataCenter.setPageSize(100);
		IPage<KhyPackage> page = query.page(packageService, KhyPackage.class, dataCenter, queryWrapper);
		return Result.ok(page.getRecords());
	}

	@GetMapping(value = "/getOrderByMyType")
	public Result<?> getOrderByMyType(@RequestParam(name="type",required=true) String type, @RequestParam(name="userNo",required=true) String userNo) {
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<KhyPackage>();
		if ("0".equals(type)) {//我的订单
			queryWrapper.lambda().eq(KhyPackage::getUserNo, userNo);
		} else if ("1".equals(type)) {//我的寄件
			queryWrapper.lambda().eq(KhyPackage::getSenderPhone, userNo);
		} else {//我的收件
			queryWrapper.lambda().eq(KhyPackage::getConsigneePhone, userNo);
		}
		queryWrapper.lambda().orderByDesc(KhyPackage::getOrderTime);
		return Result.ok(packageService.list(queryWrapper));
	}

	@GetMapping(value = "/getOrderByTallyClerk")
	public Result<?> getOrderByTallyClerk(@RequestParam(name="tallyClerk",required=true) String tallyClerk) {
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<KhyPackage>();
		queryWrapper.lambda().eq(KhyPackage::getTallyClerk, tallyClerk)
			.eq(KhyPackage::getPackageState, KhyConstants.快递状态_已揽收.getCode())
			.isNull(KhyPackage::getTransportId)
			.orderByDesc(KhyPackage::getOrderTime);
		return Result.ok(packageService.list(queryWrapper));
	}

	@GetMapping(value = "/getOrderLogisticsById")
	public Result<?> getOrderLogisticsById(@RequestParam(name="keyId",required=true) String keyId) {
		QueryWrapper<KhyPackageLogistics> queryWrapper = new QueryWrapper<KhyPackageLogistics>();
		queryWrapper.lambda().eq(KhyPackageLogistics::getPackageId, keyId)
			.orderByAsc(KhyPackageLogistics::getLogisticsTime);
		return Result.ok(packageLogisticsService.list(queryWrapper));

	}

	@GetMapping(value = "/finishOrderByPackageNo")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> finishOrderByPackageNo(@RequestParam(name="packageNo",required=true) String packageNo,
			@RequestParam(name="userNo",required=false) String userNo, @RequestParam(name="userName",required=false) String userName) {
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(KhyPackage::getPackageNo, packageNo);
		KhyPackage khyPackage = packageService.getOne(queryWrapper, false);
		if (khyPackage != null) {
			khyPackage.setPackageState(KhyConstants.快递状态_已送达.getCode());
			khyPackage.setTallyClerkShou(userNo);
			khyPackage.setTallyClerkShouName(userName);
			packageService.updateById(khyPackage);
			
			//更新步骤表
			QueryWrapper<KhyPackageLogistics> queryWrapperLogistics = new QueryWrapper<KhyPackageLogistics>();
			queryWrapperLogistics.lambda().eq(KhyPackageLogistics::getPackageId, khyPackage.getKeyId())
				.eq(KhyPackageLogistics::getPackageState, KhyConstants.快递状态_已送达.getCode());
			packageLogisticsService.remove(queryWrapperLogistics);
			KhyPackageLogistics packageLogistics = new KhyPackageLogistics();
			packageLogistics.setPackageId(khyPackage.getKeyId());
			packageLogistics.setPackageState(KhyConstants.快递状态_已送达.getCode());
			packageLogistics.setLogisticsTime(LocalDateTime.now());
			StringBuffer sbf = new StringBuffer();
			sbf.append("揽收人：理货员");
			sbf.append(userName);
			packageLogistics.setLogisticsDesc(sbf.toString());
			packageLogisticsService.save(packageLogistics);
			
			//查询是否更新运输单
			queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(KhyPackage::getTransportId, khyPackage.getTransportId());
			List<KhyPackage> packageList = packageService.list(queryWrapper);
			boolean isUpdate = true;
			for (KhyPackage packageInfo : packageList) {
				if (!KhyConstants.快递状态_已送达.getCode().equals(packageInfo.getPackageState())) {
					isUpdate = false;
					break;
				}
			}
			if (isUpdate) {
				UpdateWrapper<KhyTransport> updateWrapper = new UpdateWrapper<>();
				updateWrapper.lambda().eq(KhyTransport::getKeyId, khyPackage.getTransportId())
					.set(KhyTransport::getTransportState, KhyConstants.运输单状态_已送达.getCode())
					.set(KhyTransport::getTallyClerkShou, userNo)
					.set(KhyTransport::getTallyClerkShouName, userName)
					.set(KhyTransport::getEndTime, LocalDateTime.now());
				transportService.update(updateWrapper);
			}
			
			//发送用户提醒短信
			JSONObject jsonObject=new JSONObject();
			jsonObject.put("phoneNumbers",khyPackage.getConsigneePhone());
            jsonObject.put("name", khyPackage.getPackageNo());
            jsonObject.put("station", khyPackage.getEndStationName());
			try {
				SendSmsController.sendReminderSms(jsonObject);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			return Result.ok();
		} else {
			return Result.error("快递单未找到");
		}

	}


	@GetMapping(value = "/finishOrderById")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> finishOrderById(@RequestParam(name="keyId",required=true) String keyId,
			@RequestParam(name="userNo",required=true) String userNo, @RequestParam(name="userName",required=true) String userName) {
		QueryWrapper<KhyPackage> queryWrapperPackage = new QueryWrapper<>();
		queryWrapperPackage.lambda().eq(KhyPackage::getKeyId, keyId);
		KhyPackage khyPackage = packageService.getOne(queryWrapperPackage, false);
		if (khyPackage != null) {
			khyPackage.setPackageState(KhyConstants.快递状态_已送达.getCode());
			khyPackage.setTallyClerkShou(userNo);
			khyPackage.setTallyClerkShouName(userName);
			packageService.updateById(khyPackage);
			
			//更新步骤表
			QueryWrapper<KhyPackageLogistics> queryWrapper = new QueryWrapper<KhyPackageLogistics>();
			queryWrapper.lambda().eq(KhyPackageLogistics::getPackageId, keyId)
				.eq(KhyPackageLogistics::getPackageState, KhyConstants.快递状态_已送达.getCode());
			packageLogisticsService.remove(queryWrapper);
			KhyPackageLogistics packageLogistics = new KhyPackageLogistics();
			packageLogistics.setPackageId(keyId);
			packageLogistics.setPackageState(KhyConstants.快递状态_已送达.getCode());
			packageLogistics.setLogisticsTime(LocalDateTime.now());
			StringBuffer sbf = new StringBuffer();
			sbf.append("揽收人：理货员");
			sbf.append(userName);
			packageLogistics.setLogisticsDesc(sbf.toString());
			packageLogisticsService.save(packageLogistics);
			
			//查询是否更新运输单
			queryWrapperPackage = new QueryWrapper<>();
			queryWrapperPackage.lambda().eq(KhyPackage::getTransportId, khyPackage.getTransportId());
			List<KhyPackage> packageList = packageService.list(queryWrapperPackage);
			boolean isUpdate = true;
			for (KhyPackage packageInfo : packageList) {
				if (!KhyConstants.快递状态_已送达.getCode().equals(packageInfo.getPackageState())) {
					isUpdate = false;
					break;
				}
			}
			if (isUpdate) {
				UpdateWrapper<KhyTransport> updateWrapper = new UpdateWrapper<>();
				updateWrapper.lambda().eq(KhyTransport::getKeyId, khyPackage.getTransportId())
					.set(KhyTransport::getTransportState, KhyConstants.运输单状态_已送达.getCode())
					.set(KhyTransport::getTallyClerkShou, userNo)
					.set(KhyTransport::getTallyClerkShouName, userName)
					.set(KhyTransport::getEndTime, LocalDateTime.now());
				transportService.update(updateWrapper);
			}
			
			//发送用户提醒短信
			JSONObject jsonObject=new JSONObject();
			jsonObject.put("phoneNumbers",khyPackage.getConsigneePhone());
            jsonObject.put("name", khyPackage.getPackageNo());
            jsonObject.put("station", khyPackage.getEndStationName());
			try {
				SendSmsController.sendReminderSms(jsonObject);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			
			
			return Result.ok();
		} else {
			return Result.error("快递单未找到");
		}
	}



	@GetMapping(value = "/transInfoConfirm")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> transInfoConfirm(@RequestParam(name="transportId",required=true) String transportId) {
		UpdateWrapper<KhyTransport> updateWrapper = new UpdateWrapper<>();
		updateWrapper.lambda().eq(KhyTransport::getKeyId, transportId)
			.set(KhyTransport::getConfirmTime, LocalDateTime.now())
			.set(KhyTransport::getTransportState, KhyConstants.运输单状态_运输中.getCode());
		transportService.update(updateWrapper);
		//更新步骤表
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(KhyPackage::getTransportId, transportId);
		List<KhyPackage> packageList = packageService.list(queryWrapper);
		List<KhyPackageLogistics> logisticsList = new ArrayList<>();
		for (KhyPackage khyPackage : packageList) {
			khyPackage.setPackageState(KhyConstants.快递状态_运输中.getCode());

			KhyPackageLogistics packageLogistics = new KhyPackageLogistics();
			packageLogistics.setPackageId(khyPackage.getKeyId());
			packageLogistics.setPackageState(KhyConstants.快递状态_运输中.getCode());
			packageLogistics.setLogisticsTime(LocalDateTime.now());
			StringBuffer sbf = new StringBuffer();
			sbf.append("已装车");
			packageLogistics.setLogisticsDesc(sbf.toString());
			logisticsList.add(packageLogistics);
		}
		packageService.updateBatchById(packageList);
		packageLogisticsService.saveBatch(logisticsList);

		return Result.ok();
	}

	@GetMapping(value = "/transInfoFinish")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> transInfoFinish(@RequestParam(name="transportId",required=true) String transportId,
			@RequestParam(name="userNo",required=true) String userNo,
			@RequestParam(name="userName",required=true) String userName) {
		UpdateWrapper<KhyTransport> updateWrapper = new UpdateWrapper<>();
		updateWrapper.lambda().eq(KhyTransport::getKeyId, transportId)
			.set(KhyTransport::getEndTime, LocalDateTime.now())
			.set(KhyTransport::getTransportState, KhyConstants.运输单状态_已送达.getCode())
			.set(KhyTransport::getTallyClerkShou, userNo)
			.set(KhyTransport::getTallyClerkShouName, userName);
		transportService.update(updateWrapper);
		//更新步骤表
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(KhyPackage::getTransportId, transportId);
		List<KhyPackage> packageList = packageService.list(queryWrapper);
		List<KhyPackageLogistics> logisticsList = new ArrayList<>();
		List<String> deleteIdList = new ArrayList<>();
		for (KhyPackage khyPackage : packageList) {
			deleteIdList.add(khyPackage.getKeyId());
		}
		//先删除步骤表数据
		QueryWrapper<KhyPackageLogistics> queryWrapperLogistics = new QueryWrapper<>();
		queryWrapperLogistics.lambda().in(KhyPackageLogistics::getPackageId, deleteIdList)
			.eq(KhyPackageLogistics::getPackageState, KhyConstants.快递状态_已送达.getCode());
		packageLogisticsService.remove(queryWrapperLogistics);
		//更新/插入
		for (KhyPackage khyPackage : packageList) {
			khyPackage.setPackageState(KhyConstants.快递状态_已送达.getCode());
			khyPackage.setTallyClerkShou(userNo);
			khyPackage.setTallyClerkShouName(userName);

			KhyPackageLogistics packageLogistics = new KhyPackageLogistics();
			packageLogistics.setPackageId(khyPackage.getKeyId());
			packageLogistics.setPackageState(KhyConstants.快递状态_已送达.getCode());
			packageLogistics.setLogisticsTime(LocalDateTime.now());
			StringBuffer sbf = new StringBuffer();
			sbf.append("已送达，揽收人：理货员");
			sbf.append(userName);
			packageLogistics.setLogisticsDesc(sbf.toString());
			logisticsList.add(packageLogistics);
		}
		packageService.updateBatchById(packageList);
		packageLogisticsService.saveBatch(logisticsList);
		
		//发送用户提醒短信
		try {
			for (KhyPackage khyPackage : packageList) {
				JSONObject jsonObject=new JSONObject();
				jsonObject.put("phoneNumbers",khyPackage.getConsigneePhone());
		        jsonObject.put("name", khyPackage.getPackageNo());
		        jsonObject.put("station", khyPackage.getEndStationName());
				SendSmsController.sendReminderSms(jsonObject);
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		return Result.ok();
	}

	@GetMapping(value = "/getOrderByTransportId")
	public Result<?> getOrderByTransportId(@RequestParam(name="transportId",required=true) String transportId) {
		QueryWrapper<KhyPackage> queryWrapper = new QueryWrapper<KhyPackage>();
		queryWrapper.lambda().eq(KhyPackage::getTransportId, transportId);
		return Result.ok(packageService.list(queryWrapper));
	}

	@GetMapping(value = "/getTransInfoByTransportState")
	public Result<?> getTransInfoByTransportState(@RequestParam(name="transportState",required=true) String transportState,
		@RequestParam(name="endStation",required=false) String endStation) {
		QueryWrapper<KhyTransport> queryWrapper = new QueryWrapper<KhyTransport>();
		queryWrapper.lambda().eq(KhyTransport::getTransportState, transportState)
			.orderByDesc(KhyTransport::getCreateTime);
		if (!StringUtils.isEmpty(endStation)) {
			queryWrapper.lambda().eq(KhyTransport::getEndStation, endStation);
		}
		return 	Result.ok(transportService.list(queryWrapper));
	}

	@PostMapping(value = "/getTransInfoByTallyClerkShou")
	public Result<?> getTransInfoByTallyClerkShou(@RequestBody DataCenter dataCenter) {
		QueryWrapper<KhyTransport> queryWrapper = new QueryWrapper<KhyTransport>();
		queryWrapper.lambda().orderByDesc(KhyTransport::getCreateTime);
		return Result.ok(query.page(transportService, KhyTransport.class, dataCenter, queryWrapper));
	}

	@PostMapping(value = "/getTransInfoByTallyClerk")
	public Result<?> getTransInfoByTallyClerk(@RequestBody DataCenter dataCenter) {
		QueryWrapper<KhyTransport> queryWrapper = new QueryWrapper<KhyTransport>();
		queryWrapper.lambda().orderByDesc(KhyTransport::getCreateTime);
		return Result.ok(query.page(transportService, KhyTransport.class, dataCenter, queryWrapper));
	}

	@GetMapping(value = "/getTransInfoByDriver")
	public Result<?> getTransInfoByDriver(@RequestParam(name="driverNo",required=true) String driverNo,	@RequestParam(name="transportState",required=false) String transportState) {
		QueryWrapper<KhyTransport> queryWrapper = new QueryWrapper<KhyTransport>();
		queryWrapper.lambda().eq(KhyTransport::getDriverNo, driverNo)
			.orderByDesc(KhyTransport::getCreateTime);
		if (!StringUtils.isEmpty(transportState)) {
			queryWrapper.lambda().eq(KhyTransport::getTransportState, transportState);
		}
		return 	Result.ok(transportService.list(queryWrapper));
	}
	
	@PostMapping(value = "/pageTransInfoByDriver")
	public Result<?> pageTransInfoByDriver(@RequestBody DataCenter dataCenter) {
		QueryWrapper<KhyTransport> queryWrapper = new QueryWrapper<KhyTransport>();
		queryWrapper.lambda().orderByDesc(KhyTransport::getCreateTime);
		return Result.ok(query.page(transportService, KhyTransport.class, dataCenter, queryWrapper));
	}

	@PostMapping(value = "/saveTransInfo")
	@Transactional(rollbackFor = Exception.class)
    public Result<?> saveTransInfo(@RequestBody JSONObject data) {
		if (data == null) {
			return Result.error("信息为空");
		}
		KhyTransport khyTransport = data.getObject("formData", KhyTransport.class);
		List<String> keyIdList = JSONObject.parseArray(JSON.toJSONString(data.get("dataList")), String.class);
		if (khyTransport == null || keyIdList == null) {
			return Result.error("信息为空");
		}
		if (StringUtils.isEmpty(khyTransport.getKeyId())) {
			khyTransport.setTransportState(KhyConstants.运输单状态_已揽收.getCode());
			khyTransport.setCreateTime(LocalDateTime.now());
			transportService.save(khyTransport);
			UpdateWrapper<KhyPackage> updateWrapper = new UpdateWrapper<>();
			updateWrapper.lambda().in(KhyPackage::getKeyId, keyIdList)
				.set(KhyPackage::getDriverNo, khyTransport.getDriverNo())
				.set(KhyPackage::getDriverName, khyTransport.getDriverName())
				.set(KhyPackage::getPlateNo, khyTransport.getPlateNo())
				.set(KhyPackage::getTransportId, khyTransport.getKeyId());
			packageService.update(updateWrapper);
		} else {
			transportService.updateById(khyTransport);
			UpdateWrapper<KhyPackage> updateWrapper = new UpdateWrapper<>();
			updateWrapper.lambda().in(KhyPackage::getKeyId, keyIdList)
				.set(KhyPackage::getDriverNo, khyTransport.getDriverNo())
				.set(KhyPackage::getDriverName, khyTransport.getDriverName())
				.set(KhyPackage::getPlateNo, khyTransport.getPlateNo())
				.set(KhyPackage::getTransportId, khyTransport.getKeyId());
			packageService.update(updateWrapper);
		}
		return Result.ok();
	}

	@GetMapping(value = "/getUserOrderNotInvoice")
	public Result<?> getUserOrderNotInvoice(@RequestParam(name="userNo",required=true) String userNo) {
		return Result.ok(packageService.getUserOrderNotInvoice(userNo));
	}

	@GetMapping(value = "/getUserOrderInvoice")
	public Result<?> getUserOrderInvoice(@RequestParam(name="userNo",required=true) String userNo) {
		return Result.ok(packageService.getUserOrderInvoice(userNo));
	}

	@GetMapping(value = "/getUserInvoice")
	public Result<?> getUserInvoice(@RequestParam(name="userNo",required=true) String userNo) {
		QueryWrapper<KhyUserInvoice> queryWrapper = new QueryWrapper<KhyUserInvoice>();
		queryWrapper.lambda().eq(KhyUserInvoice::getUserNo, userNo);
		return Result.ok(userInvoiceService.list(queryWrapper));
	}

	@GetMapping(value = "/getUserInvoiceByPackageId")
	public Result<?> getUserInvoiceByPackageId(@RequestParam(name="packageId",required=true) String packageId) {
		QueryWrapper<KhyUserInvoice> queryWrapper = new QueryWrapper<KhyUserInvoice>();
		queryWrapper.lambda().eq(KhyUserInvoice::getPackageId, packageId);
		return Result.ok(userInvoiceService.getOne(queryWrapper, false));
	}

	@PostMapping(value = "/saveInvoice")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> saveInvoice(@RequestBody KhyUserInvoice userInvoice) {
		if(userInvoice == null) {
			return Result.error("信息为空");
		}
		if (StringUtils.isEmpty(userInvoice.getKeyId())) {
			userInvoice.setCreateTime(LocalDateTime.now());
			userInvoice.setInvoiceStatus(KhyConstants.发票开具中状态.getCode());
			userInvoiceService.save(userInvoice);
		} else {
			userInvoiceService.updateById(userInvoice);
		}
		return Result.ok();
	}


	@PostMapping(value = "/saveAddress")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> saveAddress(@RequestBody KhyUserAdress userAdress) {
		if(userAdress == null) {
			return Result.error("信息为空");
		}
		if (StringUtils.isEmpty(userAdress.getKeyId())) {
			userAdressService.save(userAdress);
		} else {
			userAdressService.updateById(userAdress);
		}
		return Result.ok(userAdress);
	}

	@GetMapping(value = "/deleteAddress")
	public Result<?> deleteAddress(@RequestParam(name="keyId",required=true) String keyId) {
		if (!StringUtils.isEmpty(keyId)) {
			userAdressService.removeById(keyId);
			return Result.ok();
		} else {
			return Result.error("Id不能为空！");
		}
	}


	@GetMapping(value = "/getUserAdress")
	public Result<?> getUserAdress(@RequestParam(name="userNo",required=true) String userNo) {
		QueryWrapper<KhyUserAdress> queryWrapper = new QueryWrapper<KhyUserAdress>();
		queryWrapper.lambda().eq(KhyUserAdress::getUserNo, userNo);
		return Result.ok(userAdressService.list(queryWrapper));
	}
	
	@GetMapping(value = "/getUserCoupon")
	public Result<?> getUserCoupon(@RequestParam(name="userNo",required=true) String userNo, 
			@RequestParam(name="couponStatus",required=false) String couponStatus) {
		QueryWrapper<KhyUserCoupon> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(KhyUserCoupon::getUserNo, userNo);
		if (!StringUtils.isEmpty(couponStatus)) {
			queryWrapper.lambda().eq(KhyUserCoupon::getCouponStatus, couponStatus);
		}
		queryWrapper.lambda().orderByDesc(KhyUserCoupon::getEndDate)
			.orderByAsc(KhyUserCoupon::getCouponStatus);
		return Result.ok(userCouponService.list(queryWrapper));
	}
	
	@GetMapping(value = "/getUserCouponById")
	public Result<?> getUserCouponById(@RequestParam(name="keyId",required=true) String keyId) {
		if (StringUtils.isEmpty(keyId)) {
			return Result.error("Id不能为空！");
		}
		QueryWrapper<KhyUserCoupon> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(KhyUserCoupon::getKeyId, keyId);
		return Result.ok(userCouponService.getOne(queryWrapper, false));
	}

}
